#include "postponedialog.h"
#include "reminder.h"

#include <QTextEdit>
#include <QtDebug>

PostponeDialog::PostponeDialog(QWidget *parent, Qt::WindowFlags f)
    : QDialog(parent, f),
      ui(new Ui::PostponeDialog)
{
    ui->setupUi(this);

    timer = 0;

    this->setAutoclose();
    this->setReminderIndex();

    connect(ui->close_pushButton, SIGNAL(clicked()), this, SLOT(close()));
    connect(ui->postpone_pushButton, SIGNAL(clicked()), this, SLOT(postpone()));
    connect(ui->postpone_spinBox, SIGNAL(valueChanged(int)), this, SLOT(stopeAutoclose(int)));
}

PostponeDialog::~PostponeDialog()
{
    if(ui) delete(ui);
}

void PostponeDialog::closeEvent(QCloseEvent *event)
{
    emit this->stopSound();
    if(ui->clear_checkBox->isChecked() && _reminder_index){
        emit this->clearHistory(_reminder_index);
    }

    this->deleteLater();
    event->accept();
}

void PostponeDialog::setDialogMsg(const QString &msg)
{
    ui->postponeTextEdit->appendPlainText(msg);
}

void PostponeDialog::postpone()
{
    emit postpone(ui->postpone_spinBox->value()*60);
    this->close();
}

void PostponeDialog::runAutoclose()
{
    if(!timer) timer = new QTimer(this);
    connect(timer, SIGNAL(timeout()), this, SLOT(autoclose()));
    timer->start(1000);

}

void PostponeDialog::stopeAutoclose(const int /*value*/)
{
    if(timer) timer->stop();
    ui->close_pushButton->setText(tr("Close"));
}

void PostponeDialog::autoclose()
{
    if(_autoclose){
        ui->close_pushButton->setText(tr("Close (%1)").arg(_autoclose--));
    }
    else {
        ui->close_pushButton->animateClick();
    }
}

void PostponeDialog::disablePostpone(const bool disable)
{
    ui->postpone_pushButton->setDisabled(disable);
    ui->postpone_spinBox->setDisabled(disable);
}

void PostponeDialog::setReminderIndex(const int index)
{
    _reminder_index = index;
    ui->clear_checkBox->setVisible(_reminder_index);
    ui->postpone_pushButton->setHidden(_reminder_index);
    ui->postpone_spinBox->setHidden(_reminder_index);
}
